package org.administer.util;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/file")
@CrossOrigin(value = "*")
public class FileUploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public String fileUpload(MultipartFile picture) throws Exception {
        if (!picture.isEmpty()) {
            //上传文件地址
            String path = "/images";
            System.out.println("文件名称"+picture.getOriginalFilename());
            //上传文件名
            String filename = picture.getOriginalFilename();
            File filepath = new File(path, filename);
            //判断路径是否存在，没有就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文档中
            File file1 = new File(path + File.separator + filename);
            picture.transferTo(file1);
            Map<String, Object> res = new HashMap<>();
            //返回的是一个url对象
            res.put("url", file1);
        }
        return null;
    }

}
